from re import findall
import pymysql as MySQLdb
import requests
import time
import json

"""
[data响应数据]
city	"上海"
cityEn	"shanghai"
country	"中国"
countryEn	"China"
update_time	"2021-12-30 13:48:54"
data […] 7天数据
    day	"30日（星期四）"
    date	"2021-12-30"
    week	"星期四"
    wea	"晴"
    wea_img	"qing"
    wea_day	"晴"
    wea_day_img	"qing"
    wea_night	"晴"
    wea_night_img	"qing"
    tem	"8℃"
    tem1	"9℃"
    tem2	"2℃"
    humidity	"22%"
    visibility	"11km"
    pressure	"1029"
    win	[…] # 可能存在多个风向数据，字符串数组类型
        0	"北风"
        1	"北风"
    win_speed	"<3级"
    win_meter	"3km/h"
    sunrise	"06:52"
    sunset	"17:00"
    air	"130"
    air_level	"轻度污染"
    air_tips	"儿童、老年人及心脏病、呼吸系统疾病患者应尽量减少体力消耗大的户外活动。"
    alarm	{…} # 警报
        alarm_type	""
        alarm_level	""
        alarm_content	""
    hours	[…] # 小时数据
        0
            hours	"13时"
            wea	"晴"
            wea_img	"qing"
            tem	"8"
            win	"北风"
            win_speed	"<3级"
    index	[…] # 指数信息列表，有6种分别是，紫外线，减肥，血糖，穿衣，洗车，空气污染
        0 # 单个指数信息
            title	"紫外线指数"
            level	"强"
            desc	"涂擦SPF大于15、PA+防晒护肤品。"

[now响应数据]
cityid	"101020100"
date	"2021-12-30"
week	"星期四"
update_time	"2021-12-30 14:56"
city	"上海"
cityEn	"shanghai"
country	"中国"
countryEn	"China"
wea	"晴"
wea_img	"qing"
tem	"9"
tem1	"9"
tem2	"2"
win	"东北风"
win_speed	"1级"
win_meter	"2km/h"
humidity	"21%"
visibility	"12km"
pressure	"1029"
air	"104"
air_pm25	"104"
air_level	"轻度污染"
air_tips	"儿童、老年人及心脏病、呼吸系统疾病患者应尽量减少体力消耗大的户外活动。"
alarm	{…}
    alarm_type	""
    alarm_level	""
    alarm_content	""
"""

# data
data_url = 'https://tianqiapi.com/api?version=v1&appid=75437651&appsecret=Pf48jMz8&cityid=101020100'

# now
now_url = 'https://www.tianqiapi.com/api?version=v6&appid=75437651&appsecret=Pf48jMz8&cityid=101020100'


def get_wea_data(db, logger, table={}):
    """
    Now: 获取天气实时数据 存放至 table['day'] table['hour'] table['now'] 表中
    """
    try:
        req = requests.post(url=now_url, data=json.dumps({}), headers={})
        resp = req.text
        res = json.loads(resp)
        if (res['cityid'] == ''):
            logger.warning('>>> [get_now_data()] cityid is "" ')
        else:
            logger.info('>>> [get_now_data()] cityid is ' + res['cityid'])
            cityid = res['cityid']
            date = res['date']
            week = res['week']
            city = res['city']
            cityEn = res['cityEn']
            country = res['country']
            countryEn = res['countryEn']
            wea = res['wea']
            wea_img = res['wea_img']
            tem = res['tem']
            tem1 = res['tem1']
            tem2 = res['tem2']
            win = res['win']
            win_speed = res['win_speed']
            win_meter = res['win_meter']
            humidity = res['humidity']
            visibility = res['visibility']
            pressure = res['pressure']
            air = res['air']
            air_pm25 = res['air_pm25']
            air_level = res['air_level']
            air_tips = res['air_tips']
            delete_flag = 0
            update_time = create_time = time.strftime("%Y-%m-%d %H:%M:%S",
                                                      time.localtime())
            print(update_time + ' Weather 数据新增')
            res_count = db.selectDB(
                "SELECT nid FROM `%s` WHERE cityid = '%s' AND date = '%s'"
                % (table['now'], cityid, date))
            if (len(res_count) > 0):
                have_id = res_count[0]['nid']
                logger.info('>>> [get_now_data()] have data: ' + str(have_id))
                db.updateDB('''
                UPDATE `%s`
                    SET
                    `wea` = '%s',
                    `wea_img` = '%s',
                    `tem` = '%s',
                    `tem1` = '%s',
                    `tem2` = '%s',
                    `win` = '%s',
                    `win_speed` = '%s',
                    `win_meter` = '%s',
                    `humidity` = '%s',
                    `visibility` = '%s',
                    `pressure` = '%s',
                    `air` = '%s',
                    `air_pm25` = '%s',
                    `air_level` = '%s',
                    `air_tips` = '%s',
                    `update_time` = '%s'
                    WHERE `nid` = %d;
                ''' % (table['now'], wea, wea_img, tem, tem1, tem2, win, win_speed,
                       win_meter, humidity, visibility, pressure, air,
                       air_pm25, air_level, air_tips, update_time, have_id))
            else:
                db.insertDB('''INSERT INTO `%s` (
                    `cityid`,
                    `date`,
                    `week`,
                    `city`,
                    `cityEn`,
                    `country`,
                    `countryEn`,
                    `wea`,
                    `wea_img`,
                    `tem`,
                    `tem1`,
                    `tem2`,
                    `win`,
                    `win_speed`,
                    `win_meter`,
                    `humidity`,
                    `visibility`,
                    `pressure`,
                    `air`,
                    `air_pm25`,
                    `air_level`,
                    `air_tips`,
                    `delete_flag`,
                    `update_time`,
                    `create_time`
                ) VALUES (
                '%s', '%s', '%s', '%s', '%s',
                '%s', '%s', '%s', '%s', '%s',
                '%s', '%s', '%s', '%s', '%s',
                '%s', '%s', '%s', '%s', '%s',
                '%s', '%s', b'%u', '%s', '%s');
            ''' % (table['now'], cityid, date, week, city, cityEn, country, countryEn, wea,
                   wea_img, tem, tem1, tem2, win, win_speed, win_meter,
                   humidity, visibility, pressure, air, air_pm25, air_level,
                   air_tips, delete_flag, update_time, create_time))
    except Exception as e:
        logger.error(">>> [get_now_data()] error: %s", e)
    else:
        pass

    """
    Data: 获取今日  未来七天  小时数据 
    """
    try:
        req = requests.post(url=data_url, data=json.dumps({}), headers={})
        resp = req.text
        res = json.loads(resp)
        if (res['cityid'] == ''):
            logger.warning('>>> [get_day_data()] cityid is "" ')
        else:
            logger.info('>>> [get_day_data()] cityid is ' + res['cityid'])
            cityid = res['cityid']
            city = res['city']
            cityEn = res['cityEn']
            country = res['country']
            countryEn = res['countryEn']
            update_time = res['update_time']
            data = res['data']
            for d in data:
                day = d['day']
                date = d['date']
                week = d['week']
                wea = d['wea']
                wea_img = d['wea_img']
                wea_day = d['wea_day']
                wea_day_img = d['wea_day_img']
                wea_night = d['wea_night']
                wea_night_img = d['wea_night_img']
                tem = d['tem']
                tem1 = d['tem1']
                tem2 = d['tem2']
                win = json.dumps(d['win'], ensure_ascii=False)
                win_speed = d['win_speed']
                win_meter = d['win_meter']
                humidity = d['humidity']
                visibility = d['visibility']
                pressure = d['pressure']
                sunrise = d['sunrise']
                sunset = d['sunset']
                air = d['air']
                air_level = d['air_level']
                air_tips = d['air_tips']
                delete_flag = 0
                create_time = time.strftime("%Y-%m-%d %H:%M:%S",
                                            time.localtime())
                hours = d['hours']
                db.deleteDB("DELETE FROM `%s` WHERE city_id = '%s' AND day_id = '%s';"
                            % (table['hour'], cityid, date))
                for h in hours:
                    h_hours = h['hours']
                    h_wea = h['wea']
                    h_wea_img = h['wea_img']
                    h_tem = h['tem']
                    h_win = h['win']
                    h_win_speed = h['win_speed']
                    db.insertDB('''INSERT INTO `%s` ( 
                        `city_id`, 
                        `day_id`, 
                        `hours`, 
                        `wea`, 
                        `wea_img`, 
                        `tem`, 
                        `win`, 
                        `win_speed`, 
                        `delete_flag`, 
                        `update_time`, 
                        `create_time` 
                    ) VALUES ( '%s', '%s', '%s', '%s', '%s', 
	                '%s', '%s', '%s', b'%u', '%s', '%s' );
                    ''' % (table['hour'], cityid, date, h_hours, h_wea, h_wea_img, h_tem,
                           h_win, h_win_speed, delete_flag, update_time,
                           create_time))

                res_count = db.selectDB(
                    "SELECT di_id FROM `%s` WHERE city_id = '%s' AND date = '%s'"
                    % (table['day'], cityid, date))
                if (len(res_count) > 0):
                    have_id = res_count[0]['di_id']
                    logger.info('>>> [get_day_data()] have data: ' +
                                str(have_id))
                    db.updateDB('''
                    UPDATE `%s` 
                        SET 
                        `wea` = '%s',
                        `wea_img` = '%s',
                        `wea_day` = '%s',
                        `wea_day_img` = '%s',
                        `wea_night` = '%s',
                        `wea_night_img` = '%s',
                        `tem` = '%s',
                        `tem1` = '%s',
                        `tem2` = '%s',
                        `win` = '%s',
                        `win_speed` = '%s',
                        `win_meter` = '%s',
                        `humidity` = '%s',
                        `visibility` = '%s',
                        `pressure` = '%s',
                        `sunrise` = '%s',
                        `sunset` = '%s',
                        `air` = '%s',
                        `air_level` = '%s',
                        `air_tips` = '%s',
                        `update_time` = '%s'
                        WHERE `di_id` = %d;
                    ''' % (table['day'], wea, wea_img, wea_day, wea_day_img, wea_night,
                           wea_night_img, tem, tem1, tem2, win, win_speed,
                           win_meter, humidity, visibility, pressure, sunrise,
                           sunset, air, air_level, air_tips, update_time,
                           have_id))
                else:
                    db.insertDB('''INSERT INTO `%s` (
                        `city_id`,
                        `day`,
                        `date`,
                        `week`,
                        `wea`,
                        `wea_img`,
                        `wea_day`,
                        `wea_day_img`,
                        `wea_night`,
                        `wea_night_img`,
                        `tem`,
                        `tem1`,
                        `tem2`,
                        `win`,
                        `win_speed`,
                        `win_meter`,
                        `humidity`,
                        `visibility`,
                        `pressure`,
                        `sunrise`,
                        `sunset`,
                        `air`,
                        `air_level`,
                        `air_tips`,
                        `delete_flag`,
                        `update_time`,
                        `create_time` 
                    ) VALUES (
                    '%s', '%s', '%s', '%s', '%s', 
                    '%s', '%s', '%s', '%s', '%s', 
                    '%s', '%s', '%s', '%s', '%s', 
                    '%s', '%s', '%s', '%s', '%s', 
                    '%s', '%s', '%s', '%s', 
                    b'%u', '%s', '%s');
                ''' % (table['day'], cityid, day, date, week, wea, wea_img, wea_day,
                       wea_day_img, wea_night, wea_night_img, tem, tem1, tem2,
                       win, win_speed, win_meter, humidity, visibility,
                       pressure, sunrise, sunset, air, air_level, air_tips,
                       delete_flag, update_time, create_time))

    except Exception as e:
        logger.error(">>> [get_day_data()] error: %s", e)
    else:
        pass

